package com.sjz.myfrist;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

/***
 * 操作数据库  创建和删除
 */
public class SqliteDb extends AppCompatActivity implements View.OnClickListener {
    private TextView tv_database;
    private String mDatabaseName;
    private String desc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sqlite_db);
        tv_database = findViewById(R.id.sqlite_tv_database);
        findViewById(R.id.sqlite_btn_database_create).setOnClickListener(this);
        findViewById(R.id.sqlite_btn_database_delete).setOnClickListener(this);

//        生成一个测试数据库的完整路径
        mDatabaseName = getFilesDir() + "/user.db";
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
//            创建或打开数据库，数据库如果不存在则创建
            case R.id.sqlite_btn_database_create:
                SQLiteDatabase db = openOrCreateDatabase(mDatabaseName, Context.MODE_PRIVATE,null);
                desc = String.format("数据库%s创建%s",db.getPath(),(db != null) ? "成功":"失败");
                tv_database.setText(desc);
                break;
            case R.id.sqlite_btn_database_delete:
                //删除数据库
                boolean result = deleteDatabase(mDatabaseName);
                desc = String.format("数据库%s删除%s",mDatabaseName,result? "成功":"失败");
                tv_database.setText(desc);
                break;
        }
    }

}